local Util = require("common.Util")
local ObjHuman = require("core.ObjHuman")
local InnerMsg = require("core.InnerMsg")
local UnionWarDBLogic = require("union.UnionWarDBLogic")
local UnionWarLogic = require("union.UnionWarLogic")
local MiddleManager = require("middle.MiddleManager")
local CombatDefine = require("combat.CombatDefine")
local UnionWarExcel = require("excel.unionWar")

function WL_UNION_WAR_REFRESH(fd,msg)
    UnionWarLogic.refreshData(fd)
end

function LW_UNION_WAR_ADD(fd, msg)
    UnionWarDBLogic.addUnion(fd,msg)
end

function LW_UNION_WAR_MEMBER(fd, msg)
    print("   LW_UNION_WAR_MEMBER !!!!!")
    UnionWarDBLogic.addUnionMember(fd,msg)
end

local function fontWarData(net,data)
    if data then
        net.unionUuid = data.unionUuid
        net.name = data.name
        net.bannerID = data.bannerID
        net.zhandouli = data.zhandouli
        net.star = data.star
        net.svrName = data.svrName
        net.member = {}
        local len = 0
        local member
        for k,_ in pairs(data.member) do
            member = UnionWarDBLogic.getMember(k)
            if member then
                len = len + 1
                net.member[len] = {}
                net.member[len].index = member.index
                net.member[len].uuid = k
                net.member[len].name = member.name
                net.member[len].star = member.defendStar 
                net.member[len].zhandouli = member.rolebase.zhandouli
                net.member[len].rank = member.rank or 0
            end
           
        end
    end
end
function LW_UNION_WAR_QUERY(fd,msg)
    local db = UnionWarDBLogic.getDB()
    local union = db.unionList[msg.unionUuid]
    local msgRet = InnerMsg.wl.WL_UNION_WAR_QUERY
    msgRet.uuid = msg.uuid
    msgRet.attacker = {}
    msgRet.defender = {}
    if not union then
        msgRet.cnt = 0
        msgRet.state = UnionWarLogic.UNION_STATE2
    elseif union.targetID then
        local member = UnionWarDBLogic.getMember(msg.uuid)
        msgRet.cnt = member and member.attackCnt or 0    
        msgRet.state = UnionWarLogic.UNION_STATE1
        local targetUnion = db.unionList[union.targetID]
        fontWarData(msgRet.attacker,union)
        fontWarData(msgRet.defender,targetUnion)
    else
        local member = UnionWarDBLogic.getMember(msg.uuid)
        msgRet.cnt = member and member.attackCnt or 0
        msgRet.state = UnionWarLogic.UNION_STATE3
    end

    InnerMsg.sendMsg(fd, msgRet)
end

function WL_UNION_WAR_QUERY(fd, msg)
    local human = ObjHuman.onlineUuid[msg.uuid]
    if human == nil then
        return  
    end
    UnionWarLogic.WLQuery(human,msg)
end

function LW_UNION_WAR_BUFF_QUERY(fd, msg)
    local db = UnionWarDBLogic.getDB()
    local union = db.unionList[msg.unionUuid]
    local msgRet = InnerMsg.wl.WL_UNION_WAR_BUFF_QUERY
    msgRet.uuid = msg.uuid
    msgRet.unionUuid = msg.unionUuid
    msgRet.buffLv = union and union.buffLv or 0
    InnerMsg.sendMsg(fd, msgRet)
end

function WL_UNION_WAR_BUFF_QUERY(fd, msg)
    if msg.uuid == "" then
        UnionWarLogic.WLBuffQuery(nil,msg)
    else
        local human = ObjHuman.onlineUuid[msg.uuid]
        if human == nil then
            return  
        end
        UnionWarLogic.WLBuffQuery(human,msg)
    end   
end

function LW_UNION_WAR_MATCH(fd,msg)
    local matchList,db = UnionWarDBLogic.getMatchList()

    if not matchList or #matchList == 0 then
        return
    end
    
    local unionList = db.unionList
    local svrIndex = MiddleManager.FD_2_SVRINDEX[fd]
    local unionUuid = msg.unionUuid

    local tb = {}
    local len = 0
    for k,v in ipairs(db.matchList) do
        local union1 = unionList[v[1]]
        local union2 = unionList[v[2]]
        if union1 and union2 then
            len = len + 1
            tb[len]= {}
        
            if union2.svrIndex == svrIndex then
                union1,union2 = union2,union1
            end
            tb[len][1] = {union1.name,union1.jifen, union1.rank}
            tb[len][2] = {union2.name,union2.jifen, union2.rank}
            tb[len][3] = {union1.unionUuid,union2.unionUuid,union1.svrName, union2.svrName}
        end
        
    end
    table.sort(tb,function(a,b) 
        if a[3][1] == unionUuid or a[3][2] == unionUuid then
            return true
        else
            return a[3] == svrIndex
        end
    end)

    local msgRet = InnerMsg.wl.WL_UNION_WAR_MATCH
    msgRet.uuid = msg.uuid
    msgRet.list = {}
    len = 0
    for k,v in ipairs(tb) do
        len = len + 1
        msgRet.list[len] = {v[1],v[2], v[3]}
    end
    InnerMsg.sendMsg(fd, msgRet)
end

function WL_UNION_WAR_MATCH(fd,msg)
    local human = ObjHuman.onlineUuid[msg.uuid]
    if human == nil then
        return  
    end
    UnionWarLogic.WLMatch(human,msg)
end

local function fontAtkHeroList(net, data)
    net.objList = {}
 --   Util.printTable(data.objList)
    for i = 1 ,CombatDefine.COMBAT_HERO_CNT do
        local obj = data.objList[i]
        if obj then
            net.objList[i] = {}
            net.objList[i].id = obj.id
            net.objList[i].bagIndex = obj.bagIndex or  0
            net.objList[i].lv = obj.lv
            net.objList[i].star = obj.star
        end
    end
end

local function fontHeroList(net,data)
    net.index = data.index
    net.defendStar = data.defendStar
    net.defendCnt = data.defendCnt
    net.loseBuff = data.loseBuff or 0
    net.zhandouli = data.rolebase.zhandouli
    if data.monsterOutID then
        net.monsterOutID = data.monsterOutID
    end
    net.objList = {}
    for i = 1,CombatDefine.COMBAT_HERO_CNT do
        local obj = data.objList[i]
        if obj then
            net.objList[i] = {}
            net.objList[i].id = obj.id
            net.objList[i].bagIndex = obj.bagIndex or  0
            net.objList[i].lv = obj.lv
            net.objList[i].star = obj.star
        end
    end
end

FIGHT1 = 1  --可以挑战
FIGHT2 = 2  --次数不足
FIGHT3 = 3  --重复挑战
FIGHT4 = 4  --对手被挑战中
FIGHT5 = 5  --星数不足
FIGHT6 = 6  --无参与
local function canFight(attackUuid,defendUuid,attackUnion,defendUnion)
    
    local attacker = UnionWarDBLogic.getMember(attackUuid)
    --判断次数
    if not attacker then
        return FIGHT6
    end
    
    if attacker.attackCnt >= UnionWarExcel.define[1].cnt then
        return FIGHT2
    end

    if attackUnion.combat[attackUuid] then
        if os.time() -  attackUnion.combat[attackUuid][3] >= 60 * 5 then
            attackUnion.combat[attackUuid] = nil
        else
            return FIGHT3
        end       
    end

    for k,v in pairs(attackUnion.combat) do
        if v[1] == defendUuid then
            return FIGHT4
        end
    end
    
    local defender = UnionWarDBLogic.getMember(defendUuid)
    if defender.defendStar <= 0 and defender.loseBuff and defender.loseBuff >= UnionWarLogic.UNION_FEIXU_CNT then
        return FIGHT5
    end

    return FIGHT1
end

function LW_UNION_WAR_INFO(fd,msg)
    local db = UnionWarDBLogic.getDB()
    local attackUnion = db.unionList[msg.attackUnionUuid]
    local union = db.unionList[attackUnion.targetID]
    local target = UnionWarDBLogic.getMember(msg.targetUuid)
    local state = canFight(msg.uuid,msg.targetUuid,attackUnion,union)
    local msgRet = InnerMsg.wl.WL_UNION_WAR_INFO
    msgRet.unionUuid = msg.unionUuid
    msgRet.uuid = msg.uuid
    if state == 6 then
        msgRet.cnt = 0
    else
        local member = UnionWarDBLogic.getMember(msg.uuid)
        msgRet.cnt = member and member.attackCnt or 0
    end
    msgRet.target = {}
    fontHeroList(msgRet.target,target)
    msgRet.target.uuid = msg.targetUuid
    msgRet.target.svrIndex = union.svrIndex

    msgRet.index = target.index
    msgRet.canFight = state
    InnerMsg.sendMsg(fd, msgRet)
end

function WL_UNION_WAR_INFO(fd,msg)
    local human = ObjHuman.onlineUuid[msg.uuid] 
    if human == nil then
        return  
    end
    UnionWarLogic.WLInfo(human,msg)  
end

function LW_UNION_WAR_FIGHT(fd,msg)
    local db = UnionWarDBLogic.getDB()
    local attackUnion = db.unionList[msg.unionUuid]
    local defendUnion = db.unionList[attackUnion.targetID]
    local msgRet = InnerMsg.wl.WL_UNION_WAR_FIGHT
    msgRet.uuid = msg.attackUuid
    local state = canFight(msg.attackUuid,msg.defendUuid,attackUnion,defendUnion)
    msgRet.state = state
    if state == FIGHT1 then
        attackUnion.combat[msg.attackUuid] = {msg.defendUuid,msg.diff,os.time()}

        local defender = UnionWarDBLogic.getMember(msg.defendUuid)
        msgRet.defender = Util.copyTable(defender)
        msgRet.defender.uuid = msg.defendUuid
    else
        msgRet.defender = {}
    end
    msgRet.diff = msg.diff
    msgRet.name = defendUnion.name
    InnerMsg.sendMsg(fd, msgRet)    
end

function WL_UNION_WAR_FIGHT(fd,msg)
    local human = ObjHuman.onlineUuid[msg.uuid]
    if human == nil then
        return  
    end
    UnionWarLogic.WLFight(human,msg)
end

function LW_UNION_WAR_FIGHT_END(fd,msg)
    local atkUnion,defender,cnt,isFeixu,addStar, diff = UnionWarDBLogic.onFightEnd(msg)
    if not atkUnion then return end
    local db = UnionWarDBLogic.getDB()
    local defendUnion = db.unionList[atkUnion.targetID]

    local msgRet = InnerMsg.wl.WL_UNION_WAR_FIGHT_END
    msgRet.unionStar = atkUnion.star
    msgRet.defender = Util.copyTable(defender)
   -- msgRet.defendStar = defender.defendStar
   -- msgRet.defIndex = defender.index
    msgRet.diff =  diff
    msgRet.uuid = msg.uuid
    msgRet.cnt = cnt
    msgRet.addStar = addStar
    msgRet.isFeixu = isFeixu and 1 or 0
    msgRet.defUnionName = defendUnion.name
    msgRet.combatInfo = Util.copyTable(msg.combatInfo)
    InnerMsg.sendMsg(fd, msgRet)

    if addStar and addStar > 0 then
        -- 星级 同步
        local db = UnionWarDBLogic.getDB()
        local defendUnion = db.unionList[atkUnion.targetID]
        local msgRet2 = InnerMsg.wl.WL_UNION_WAR_FIGHT_TONGZHI    
        -- 给 攻击方公会的 在线玩家 刷新最新的星级数据
        msgRet2.unionUuid = msg.unionUuid
        msgRet2.atkUnion =  msg.unionUuid
        msgRet2.defUnion = atkUnion.targetID
        msgRet2.atkUnionStar =  atkUnion.star
        msgRet2.atkUuid = msg.uuid
        msgRet2.defUuid = defender.rolebase.uuid
        msgRet2.defStar = defender.defendStar
        msgRet2.defIndex = defender.index
     
        InnerMsg.sendMsg(fd, msgRet2)

        local defFd = MiddleManager.getFDBySvrIndex(defendUnion.svrIndex)
        if defFd then
            -- 给 被打方公会的 在线玩家 刷新 最新的星级数据
            msgRet2.unionUuid = atkUnion.targetID
            InnerMsg.sendMsg(defFd, msgRet2)
        end
    end

    if isFeixu and addStar == 0 then
        local msgRet3 = InnerMsg.wl.WL_UNION_WAR_BUFF_QUERY
        msgRet3.uuid = ""
        msgRet3.unionUuid = msg.unionUuid
        msgRet3.buffLv = atkUnion and atkUnion.buffLv or 0
        InnerMsg.sendMsg(fd, msgRet3)
    end
    
end

function WL_UNION_WAR_FIGHT_END(fd,msg)
    local human = ObjHuman.onlineUuid[msg.uuid]
    if human == nil then
        return  
    end
    UnionWarLogic.WLFightEnd(human,msg)
end


function WL_UNION_WAR_FIGHT_TONGZHI(fd, msg)
    UnionWarLogic.WLFightTongzhi(msg)
end

function fontAtkLogMsg(msgRet, log, attacker, defender)
    local len = #msgRet.list + 1
    local name = attacker.monsterOutID and attacker.rolebase.name or attacker.name
    local defName = defender.monsterOutID and defender.name or defender.rolebase.name
    name = name or ""
    defName = defName or ""
     --时间，结果，攻击者名字，防守者名字，星数，积分 , 进攻者公会
    msgRet.list[len] = {log[1], log[2], name,defName , log[7],log[8], log[3], log[11],log[12]}
end

function LW_UNION_WAR_ATKLOG(fd,msg)
    local db = UnionWarDBLogic.getDB()
    local union = db.unionList[msg.unionUuid]
    if not union then
        return
    end
    local type = msg.type
    local msgRet = InnerMsg.wl.WL_UNION_WAR_ATKLOG
    msgRet.uuid = msg.uuid
    msgRet.type = type
    msgRet.list = {}
    -- ret 1 攻占成功 1 攻占废墟成功 3 防守成功 4 防守失败
    if type == 1 then
        local attacker = UnionWarDBLogic.getMember(msg.uuid)
        if attacker and attacker.winLog then
            for i = 1,#attacker.winLog do
                local log = db.log[attacker.winLog[i]]
                local attackUnion = db.unionList[log[3]]
                local attacker2 = UnionWarDBLogic.getMember(log[5])
                local defendUnion = db.unionList[log[4]]
                local defender2 = UnionWarDBLogic.getMember(log[6])
                fontAtkLogMsg(msgRet, log, attacker2, defender2)    
            end           
        end
    elseif type == 0 then
        local len = 0
        for i = 1, #union.log do
            local log = db.log[union.log[i]]
            local attackUnion = db.unionList[log[3]]
            local attacker = UnionWarDBLogic.getMember(log[5])
            local defendUnion = db.unionList[log[4]]
            local defender = UnionWarDBLogic.getMember(log[6])
            if  log[2] then
                len = len + 1
                fontAtkLogMsg(msgRet, log, attacker, defender)    
                if len >= 100 then
                    break
                end
            end              
        end
    end

    
    InnerMsg.sendMsg(fd, msgRet)
end

function WL_UNION_WAR_ATKLOG(fd,msg)
    local human = ObjHuman.onlineUuid[msg.uuid]
    if human == nil then
        return  
    end
    UnionWarLogic.WLAtkLog(human,msg)
end

function LW_UNION_WAR_DEFLOG(fd,msg)
    local db = UnionWarDBLogic.getDB()
    local union = db.unionList[msg.unionUuid]
    if union.targetID ~= msg.defendUnion and msg.defendUnion ~= msg.unionUuid then 
        return
    end
    local defendUnion = db.unionList[msg.defendUnion]
    local defendUuid = msg.defendUuid
    local defender = UnionWarDBLogic.getMember(defendUuid) 
    local msgRet = InnerMsg.wl.WL_UNION_WAR_DEFLOG
    msgRet.uuid = msg.uuid
    msgRet.list = {}  
    local len = 0
    for k,v in ipairs(defender.log) do
        local videoDB = UnionWarDBLogic.getRecordDB(v)
        len = len + 1
        msgRet.list[len] = {}
        msgRet.list[len].id = v
        msgRet.list[len].upTime = videoDB.upTime
        msgRet.list[len].diff = videoDB.diff
        local attacker = videoDB.combatInfo.attacker
        msgRet.list[len].name = attacker.name
        msgRet.list[len].zhandouli = attacker.zhandouli
        msgRet.list[len].result = videoDB.combatInfo.isWin and 1 or 0
        msgRet.list[len].target = {}
        msgRet.list[len].formation = videoDB.combatInfo.atkFormation
        msgRet.list[len].videoIndex = v
        fontAtkHeroList(msgRet.list[len].target, videoDB.combatInfo)
        msgRet.list[len].target.uuid = videoDB.attackUuid
    end
    msgRet.defender = {}
    msgRet.defender.uuid = defendUuid
    fontHeroList(msgRet.defender,defender)
    InnerMsg.sendMsg(fd, msgRet)
end

function WL_UNION_WAR_DEFLOG(human,msg)
    local human = ObjHuman.onlineUuid[msg.uuid]
    if human == nil then
        return  
    end
    UnionWarLogic.WLDefLog(human,msg)
end

function LW_UNION_WAR_VIDEO(fd, msg)
    local videoDB = UnionWarDBLogic.getRecordDB(msg.index)
    local msgRet = InnerMsg.wl.WL_UNION_WAR_VIDEO
    msgRet.uuid = msg.uuid
    msgRet.combatInfo = videoDB.combatInfo
    InnerMsg.sendMsg(fd, msgRet)
end

function WL_UNION_WAR_VIDEO(fd, msg)
    local human = ObjHuman.onlineUuid[msg.uuid]
    if human == nil then
        return  
    end
    UnionWarLogic.WLVideo(human,msg)
end
